package edu.mju.controller;

import edu.mju.entity.User;
import edu.mju.service.IUserService;
import edu.mju.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author:wyp
 * @Date:2020/5/30 15:31
 */
@WebServlet("/findUser")
public class FindPasswordController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName=req.getParameter("userName");
        String passWord=req.getParameter("passWord");
        String capche = req.getParameter("inputCapche");
        String telphone = req.getParameter("telphone");
        User updateuser = new User();
        updateuser.setUserName(userName);
        updateuser.setUserPassword(passWord);
        updateuser.setUserTel(telphone);
        //获取生成的验证码
        String capCode = (String) req.getSession().getAttribute("capcode");

        //如果用户名是学号，密码是1234，正确显示你好，如果错误，显示账号或密码错误
        if(capCode != null) {
            if (capCode.equals(capche)) {
                IUserService userService = new UserServiceImpl();
                if(telphone.equals(userService.findUser(updateuser).getUserTel())) {
                    boolean reuser = userService.update(updateuser);
                    if (reuser) {
                        resp.setContentType("text/html;charSet=GBK");
                        PrintWriter out = resp.getWriter();
                        out.print("<script>alert('找回成功，请登录！'); window.location='./login' </script>");
                        out.flush();
                        out.close();
                    } else {
                        findFail(req, resp, "找回失败");
                    }
                }else {
                    findFail(req, resp, "用户名手机号不匹配！");
                }
            }else {
                findFail(req,resp,"验证码错误");
            }
        }else {
            findFail(req,resp,"验证码未生成");
        }
    }

    private void findFail(HttpServletRequest req,HttpServletResponse resp,String str) throws ServletException, IOException {
        resp.setContentType("text/html;charSet=GBK");
        PrintWriter out = resp.getWriter();
        out.print("<script>alert('"+str+"'); window.location='./forget' </script>");
        out.flush();
        out.close();
    }
}
